package com.nutiteq.labels;

import java.util.Vector;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import com.nutiteq.components.Label;
import com.nutiteq.log.Log;
import com.nutiteq.utils.Utils;

public class ClickTestLabel implements Label {
  private final Vector points = new Vector();
  private final Image close;

  public ClickTestLabel() {
    close = Utils.createImage("/close.png");
  }

  public String getLabel() {
    return "Never mind - I'm a test!";
  }

  public void paint(final Graphics g, final int screenX, final int screenY, final int displayWidth,
      final int displayHeight) {
    g.setColor(0xFFFFFFFF);
    g.fillRect(0, 0, displayWidth, 70);
    g.setColor(0xFFFF0000);
    for (int i = 0; i < points.size(); i++) {
      final Point p = (Point) points.elementAt(i);
      g.fillRect(p.x - 2, p.y - 2, 4, 4);
    }
    g.setColor(0xFF000000);
    g.drawLine(0, 70, displayWidth, 70);
    g.setFont(Font.getDefaultFont());
    g.drawString("Click on label (pointer only)", 0, 0, Graphics.TOP | Graphics.LEFT);
    g.setColor(0xFF000000);
    final int closeBoxX = displayWidth - close.getWidth() - 5;
    final int closeBoxY = 70;
    final int closeBoxW = close.getWidth() + 5;
    final int closeBoxH = close.getHeight() + 5;
    g.fillRect(closeBoxX, closeBoxY, closeBoxW, closeBoxH);
    g.setColor(0xFFFFFFFF);
    g.fillRect(closeBoxX + 1, closeBoxY, closeBoxW, closeBoxH - 1);
    g.drawImage(close, closeBoxX + 2, closeBoxY + 2, Graphics.TOP | Graphics.LEFT);
  }

  public boolean pointOnLabel(final int screenX, final int screenY, final int displayWidth,
      final int displayHeight, final int clickX, final int clickY) {
    final int closeBoxX = displayWidth - close.getWidth() - 5;
    final int closeBoxY = 70;
    final int closeBoxW = close.getWidth() + 5;
    final int closeBoxH = close.getHeight() + 5;
    return Utils.rectanglesIntersect(0, 0, displayWidth, 70, clickX, clickY, 1, 1)
        || Utils.rectanglesIntersect(closeBoxX, closeBoxY, closeBoxW, closeBoxH, clickX, clickY, 1,
            1);
  }

  public void labelClicked(final int screenX, final int screenY, final int displayWidth,
      final int displayHeight, final int clickX, final int clickY) {
    Log.debug("TestLabel click");
    if (clickY < 70) {
      points.addElement(new Point(clickX, clickY));
    } else {
      CustomCanvas.getMapDisplay().loosePlaceFocus();
    }
  }

  public com.nutiteq.components.Point getViewUpdate(final int screenX, final int screenY,
      final int displayWidth, final int displayHeight) {
    return new com.nutiteq.components.Point(0, screenY < 100 ? screenY - 100 : 0);
  }

  class Point {
    private final int x;
    private final int y;

    public Point(final int x, final int y) {
      this.x = x;
      this.y = y;
    }
  }
}
